<template>
	<view class="d-login">
		<!-- #ifdef MP-WEIXIN -->
		<view class="d-login-btn">
			<template v-if="step == 2">

				<u-button class="d-btn" type="success" shape="circle" @click='getUserProfile'>微信授权</u-button>


			</template>
			<template v-if="step == 1">
				<u-button class="d-btn" type="primary" shape="circle" open-type="getPhoneNumber"
					@getphonenumber="getphonenumber" :custom-style="customStyle">授权手机号登入</u-button>
			</template>
		</view>
		<u-toast ref="uToast" />
		<view class="d-login-btn1">
			<u-button class="d-btn" type="warning" @click="back()" shape="circle">暂不登录</u-button>
		</view>
		<!--#endif-->
		<!--#ifdef MP-TOUTIAO -->
		<view>
			<view class=""
				style="width: 90%; border-radius: 20px;background-color: white;padding: 20px;margin-left: auto;margin-right: auto;margin-top: 50%;text-align: center;">
				<u-field v-model="uForm.phone" label="手机号" placeholder="请填写手机号" required :error-message="phoneErr">
				</u-field>
				<u-field v-model="uForm.code" label="验证码" placeholder="请填写验证码" required :error-message="codeErr">
					<u-button size="mini" slot="right" type="success" @click="getCode">{{uForm.codeText}}</u-button>
				</u-field>
				<u-verification-code ref="uCode" @change="codeChange"></u-verification-code>

				<u-button @click="loginByPhone" size="medium" type="primary" :custom-style="customStyle"
					style="margin: 10px;">提交</u-button>
			</view>
		</view>
		<!--#endif-->
	</view>
</template>

<script>
	const obj = {
		0: {
			lable: '工人',
			value: 'any'
		},
		1: {
			label: '普通小中介',
			value: 'small'
		},
		2: {
			label: '专属小中介',
			value: 'small'
		},
		3: {
			label: '大中介',
			value: 'big'
		}
	};
	export default {
		data() {
			return {
				customStyle: {
					marginTop: '20px',
					background: '#5650ee'
				},
				step: 1,
				type: 1, //普通小中介
				params: {
					sex: '',
					openId: '',
					sessionKey: '',
					encryptedData: '',
					iv: '',
					hidPic: '',
					realName: '',
					recId: '',
					rId: '',
					code: '',
					type: 1
				},
				uForm: {
					phone: null,
					code: null,
					codeText: '获取验证码'
				},
			};
		},
		onLoad(e) {
			console.log(e)
			if (e && e.type) {
				this.params.type = e.type;
			}
			// this.form.rId = uni.getStorageSync('recId');
			this.recId = uni.getStorageSync('recId');
			var that = this;
			uni.getStorage({
				key: 'wxUserInfo',
				success: function(res) {
					that.step = 1
				},
				fail: res => {
					that.step = 2
				}

			});
			//#ifdef MP-TOUTIAO
			tt.login({
				force: true,
				success(res) {
					console.log(`login 调用成功${res.code} ${res.anonymousCode}`);
				},
				fail(res) {
					console.log(`login 调用失败`);
				},
			});
			//#endif
			uni.login({
				// #ifdef MP-WEIXIN
				provider: 'weixin',
				// #endif
				// #ifdef MP-TOUTIAO
				provider: 'toutiao',
				// #endif
				success: loginRes => {

					// #ifdef MP-WEIXIN
					wx.getSetting({
						success: res => {
							if (res.authSetting['scope.userInfo']) {
								// 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
								wx.getUserInfo({
									success: res => {
										// 可以将 res 发送给后台解码出 unionId
										uni.setStorageSync('wxUserInfo', res.userInfo);
									}
								})
							}
						},
					})

					this.$u.api
						.postGetWechatOpenId({
							code: loginRes.code
						})
						.then(res => {
							console.log(res, '[登录页面-获取微信openid]');
							this.params.openId = res.data.openid;
							this.params.sessionKey = res.data.session_key;
							uni.setStorageSync('openId', this.params.openId);

						})
						.catch(err => {
							console.log(err);
						});
					//#endif
				}
			});
		},
		methods: {
			back() {
				uni.reLaunch({
					url: 'index/index'
				})
			},
			// 判断用户是否登录
			postIsLogin() {
				this.$u.api
					.postIsLogin()
					.then(res => {
						if (res.code == 1000) {
							console.log(res, '[登录页面-判断用户是否登录]');
							// 获取用户信息
							this.postGetAdminInfo();
							uni.reLaunch({
								url: 'index/index'
							});
						}
					})
					.catch(err => {
						console.log(err);
					});
			},
			// 获取微信用户信息
			getuserinfo(e) {
				let that = this
				// this.params.sex = e.detail.userInfo.gender;
				// this.params.hidPic = e.detail.userInfo.avatarUrl;
				// this.params.realName = e.detail.userInfo.nickName;
				// 获取微信openidgetUserProfile:fail 
				uni.getUserInfo({
					success(res) {
						console.log(res)
						that.params.sex = res.userInfo.gender;
						that.params.hidPic = res.userInfo.avatarUrl;
						that.params.realName = res.userInfo.nickName;
						uni.setStorageSync('wxUserInfo', res.userInfo);
					}
				})
				that.postGetWechatOpenId();

			},
			getUserProfile() {
				var that = this
				wx.getUserProfile({
					desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
					success: (res) => {
						uni.setStorageSync('wxUserInfo', res.userInfo);
						console.log(res.userInfo)
						that.postGetWechatOpenId();
					}
				})
			},
			// 获取微信openid
			postGetWechatOpenId() {
				uni.login({
					provider: 'weixin',
					success: loginRes => {
						this.$u.api
							.postGetWechatOpenId({
								code: loginRes.code
							})
							.then(res => {
								console.log(res, '[登录页面-获取微信openid]');
								this.params.openId = res.data.openid;
								this.params.sessionKey = res.data.session_key;
								uni.setStorageSync('openId', this.params.openId);
								if (!!res.data.phone) {
									// 登录
									this.postLoginCheck();
								} else {
									this.step = 1;
									uni.showToast({
										title: '请授权手机号',
										icon: 'none'
									});
								}
							})
							.catch(err => {
								console.log(err);
							});
					}
				});
			},
			// 授权手机号
			getphonenumber(e) {
				console.log(e);

				if (e.detail.errMsg == 'getPhoneNumber:ok') {
					this.params.encryptedData = e.detail.encryptedData;
					this.params.iv = e.detail.iv;
					this.params.recId = uni.getStorageSync('recId');
					this.params.rId = uni.getStorageSync('recId');
					// 登录
					this.postLoginCheck();
				} else {
					uni.showToast({
						title: '若拒绝无法体验更多功能',
						duration: 2000,
						icon: 'none'
					});
				}

			},
			// 登录
			postLoginCheck() {
				let params = {
					...this.params
				};
				this.$u.api
					.postLoginCheck(params)
					.then(res => {
						if (res.status == true) {
							console.log(res, '[登录页面-登录]');
							uni.setStorageSync('token', res.data);
							// 获取用户信息
							this.postGetAdminInfo().then(res => {

								// uni.navigateBack()

							});
						}
					})
					.catch(err => {
						console.log(err);
					});
			},
			// 获取用户信息
			postGetAdminInfo() {
				return new Promise((resolve, reject) => {
					this.$u.api
						.postGetAdminInfo()
						.then(res => {
							console.log(res)
							if (res.status == true) {
								uni.setStorageSync('userPhone', res.data.phone);
								// this.$store.commit('commitUserId', res.data.id);
								uni.setStorageSync('userId', res.data.id);
								uni.setStorageSync('userInfo', res.data);
								this.$store.commit('commitUserInfo', res.data);
								switch (res.data.type) {
									case 0:
										uni.setStorageSync('role', 'any');
										uni.setStorageSync('roleType', 0);
										break;
									case 1:
										uni.setStorageSync('role', 'small');
										uni.setStorageSync('roleType', 1);
										break;
									case 2:
										uni.setStorageSync('role', 'small');
										uni.setStorageSync('roleType', 2);
									case 3:
										uni.setStorageSync('role', 'big');
										uni.setStorageSync('roleType', 3);
								}
							}
							// if (res && (res.data.type != 1 || res.data.type != 2)) {
							// 	uni.reLaunch({
							// 		url: 'apply'
							// 	})
							// } else {
							// 	uni.reLaunch({
							// 		url: './index/home'
							// 	});
							// }
							// uni.reLaunch({
							// 	url: './index/home'
							// });
							uni.navigateBack()
							resolve();
						})
						.catch(err => {
							console.log(err);
							reject();
						});
				});
			},
			codeChange(text) {
				this.uForm.codeText = text;
			},
			
			getCode() {
				if (this.$refs.uCode.canGetCode) {
					if (!this.uForm.phone) {
						uni.showToast({
							title: "请先填写手机号",
							duration: 2000,
							icon: 'none'
						});
						return
					}
					// 向后端请求验证码
					this.$u.api.bigSendSms({
						phone: this.uForm.phone
					}).then(res => {
						if (res.status == true) {
							uni.showToast({
								title: "发送成功",
							});
							this.$refs.uCode.start();
						} else {
							uni.showToast({
								title: res.msg,
								duration: 2000,
								icon: 'none'
							});
						}
					})
				} else {
					this.$u.toast('倒计时结束后再发送');
				}
			},
			loginByPhone() {
				let params = {
					phone: this.uForm.phone,
					code: this.uForm.code,
					rId: this.params.recId,
					type: this.params.type
				};
				this.$u.api
					.bigLogin(params)
					.then(res => {
						if (res.status == true) {
							console.log(res, '[登录页面-登录]');
							uni.setStorageSync('token', res.data)
							const typeItem = obj[res.type]
							// 获取用户信息
							this.$u.api
								.postGetAdminInfo()
								.then(res => {
									console.log(res, "++++++++++++")
									if (res.status == true) {
										uni.setStorageSync('userPhone', res.data.phone);
										// this.$store.commit('commitUserId', res.data.id);
										uni.setStorageSync('userId', res.data.id);
										uni.setStorageSync('userInfo', res.data);
										this.$store.commit('commitUserInfo', res.data);
										switch (res.data.type) {
											case 0:
												uni.setStorageSync('role', 'any');
												uni.setStorageSync('roleType', 0);
												break;
											case 1:
												uni.setStorageSync('role', 'small');
												uni.setStorageSync('roleType', 1);
												break;
											case 2:
												uni.setStorageSync('role', 'small');
												uni.setStorageSync('roleType', 2);
											case 3:
												uni.setStorageSync('role', 'big');
												uni.setStorageSync('roleType', 3);
										}
									}
									// if (res && (res.data.type != 1 || res.data.type != 2)) {
									// 	uni.reLaunch({
									// 		url: 'apply'
									// 	})
									// } else {
									// 	uni.reLaunch({
									// 		url: './index/home'
									// 	});
									// }
									// uni.reLaunch({
									// 	url: './index/home'
									// });
									uni.navigateBack()
								})

						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						}
					})
					.catch(err => {
						console.log(err);
					});
			}
		}
	};
</script>

<style scoped lang="scss">
	.d-login {
		position: fixed;
		top: 0;
		width: 100%;
		height: 100%;
		background: url() no-repeat left top;
		background-size: 100% auto;
		background-color: #fff;

		.d-login-btn {
			position: fixed;
			bottom: 170rpx;
			left: 0;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;

			.d-btn {
				width: 690rpx;
			}
		}

		.d-login-btn1 {
			position: fixed;
			bottom: 60rpx;
			left: 0;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;

			.d-btn {
				width: 690rpx;
			}
		}
	}
</style>
